﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text.RegularExpressions;

namespace CoolCode.Web
{
    public class PrefixableValueProvider : IDictionary<string, ValueProviderResult>
    {
        private static readonly Regex camelPrefixRegex = new Regex(@"[a-z]+", RegexOptions.Compiled);
        private static readonly Regex ucPrefixRegex = new Regex(@"\w+[\$|_][a-z]*", RegexOptions.Compiled);

        private readonly Dictionary<string, ValueProviderResult> _dictionary = new Dictionary<string, ValueProviderResult>(StringComparer.OrdinalIgnoreCase);
        private PrefixType _prefixType = PrefixType.None;

        public PrefixableValueProvider(ControllerContext controllerContext)
            : this(controllerContext, PrefixType.None)
        {
        }

        public PrefixableValueProvider(ControllerContext controllerContext, PrefixType prefixType)
        {
            _prefixType = prefixType;
            ControllerContext = controllerContext;
            if (controllerContext != null)
            {
                PopulateDictionary();
            }
        }

        public ControllerContext ControllerContext
        {
            get;
            private set;
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public int Count
        {
            get
            {
                return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Count;
            }
        }

        internal Dictionary<string, ValueProviderResult> Dictionary
        {
            get
            {
                return _dictionary;
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public bool IsReadOnly
        {
            get
            {
                return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).IsReadOnly;
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public ICollection<string> Keys
        {
            get
            {
                return Dictionary.Keys;
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public ValueProviderResult this[string key]
        {
            get
            {
                ValueProviderResult result;
                Dictionary.TryGetValue(key, out result);
                return result;
            }
            set
            {
                Dictionary[key] = value;
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public ICollection<ValueProviderResult> Values
        {
            get
            {
                return Dictionary.Values;
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public void Add(KeyValuePair<string, ValueProviderResult> item)
        {
            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Add(item);
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public void Add(string key, ValueProviderResult value)
        {
            Dictionary.Add(key, value);
        }

        private void AddToDictionaryIfNotPresent(string key, ValueProviderResult result)
        {
            if (!String.IsNullOrEmpty(key))
            {
                if (!Dictionary.ContainsKey(key))
                {
                    Dictionary.Add(key, result);
                }
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public void Clear()
        {
            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Clear();
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public bool Contains(KeyValuePair<string, ValueProviderResult> item)
        {
            return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Contains(item);
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public bool ContainsKey(string key)
        {
            return Dictionary.ContainsKey(key);
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public void CopyTo(KeyValuePair<string, ValueProviderResult>[] array, int arrayIndex)
        {
            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).CopyTo(array, arrayIndex);
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public IEnumerator<KeyValuePair<string, ValueProviderResult>> GetEnumerator()
        {
            return ((IEnumerable<KeyValuePair<string, ValueProviderResult>>)Dictionary).GetEnumerator();
        }

        private void PopulateDictionary()
        {
            CultureInfo currentCulture = CultureInfo.CurrentCulture;
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;

            // We use this order of precedence to populate the dictionary:
            // 1. Request form submission (should be culture-aware)
            // 2. Values from the RouteData (could be from the typed-in URL or from the route's default values)
            // 3. URI query string

            NameValueCollection form = ControllerContext.HttpContext.Request.Form;
            if (form != null)
            {
                string[] keys = form.AllKeys;
                foreach (string key in keys)
                {
                    string[] rawValue = form.GetValues(key);
                    string attemptedValue = form[key];
                    ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, currentCulture);
                    //Modify: make up key
                    MakeupKeyThenAddToDictionary(key,result );
                    //Origin: AddToDictionaryIfNotPresent(key, result);
                }
            }
 
            NameValueCollection queryString = ControllerContext.HttpContext.Request.QueryString;
            if (queryString != null)
            {
                string[] keys = queryString.AllKeys;
                foreach (string key in keys)
                {
                    string[] rawValue = queryString.GetValues(key);
                    string attemptedValue = queryString[key];
                    ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, invariantCulture);
                    //Modify: make up key
                    MakeupKeyThenAddToDictionary(key, result);
                    //Origin: AddToDictionaryIfNotPresent(key, result);
                }
            }
        }

        private void MakeupKeyThenAddToDictionary(string key, ValueProviderResult result)
        {
            switch (_prefixType)
            {
                case PrefixType.None:
                    AddToDictionaryIfNotPresent(key, result);
                    break;

                case PrefixType.Camel:
                    int i;
                    for (i = 0; i < key.Length; i++)
                    {
                        if (key[i] > 'z' || key[i] < 'a')
                            break;
                    }
                    if (i > 0)
                    {
                        string newKey = key.Substring(i);
                        if (Dictionary.ContainsKey(newKey))
                            Dictionary.Remove(newKey);
                        AddToDictionaryIfNotPresent(newKey, result);
                    }
                    else
                    {
                        AddToDictionaryIfNotPresent(key, result);
                    }
                    break;
                    //AddToDictionaryIfNotPresent(camelPrefixRegex.Replace(key, string.Empty), result);
                    //break;

                case PrefixType.Three:
                    if (key.Length > 3)
                    {
                        string newKey = key.Substring(3);
                        AddToDictionaryIfNotPresent(newKey, result);
                    }
                    break;

                case PrefixType.UserControl:
                    //string newKey = regex.Replace (key,string.Empty );
                    //if (Dictionary.ContainsKey(newKey))
                    //    Dictionary.Remove(newKey);
                    AddToDictionaryIfNotPresent(ucPrefixRegex.Replace (key,string.Empty ), result);
                    break;
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public bool Remove(KeyValuePair<string, ValueProviderResult> item)
        {
            return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Remove(item);
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public bool Remove(string key)
        {
            return Dictionary.Remove(key);
        }

        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public bool TryGetValue(string key, out ValueProviderResult value)
        {
            return Dictionary.TryGetValue(key, out value);
        }

        #region IEnumerable Members
        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable)Dictionary).GetEnumerator();
        }
        #endregion

    }
}
